package com.store.utils;

import com.store.controller.WebSocketServer;
import com.store.dao.RegularorderdetailMapper;
import com.store.dao.RegularsuborderMapper;
import com.store.model.*;
import com.store.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ModelAttribute;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class ScheduleUtil {

    @Autowired
    private RegularsuborderMapper regularsuborderMapper;

    @Autowired
    private RegularorderdetailMapper regularDetailMapper;

    @Autowired
    private ExpressinfoService expressinfoService;

    @Autowired
    private ExpressService expressService;

    @Autowired
    private OrderinfoService orderinfoService;

    @Scheduled(fixedRate = 1000 * 60 * 60)
    public void submitRegularOrderToPos() {

    }

    //每隔小时执行一次,把没有下单的定期购子订单都去下单,可以放到队列执行
    @Scheduled(fixedRate = 1000 * 60 * 60)
    public void createSfOrderSchedule() {
        //System.out.println("定时任务执行时间：" + dateFormat.format(new Date()));
        //先取出已经有的订单
        ExpressinfoModel expressinfoModel = new ExpressinfoModel();
        expressinfoModel.setCreateday(DateUtil.getDay());
        expressinfoModel.setErrorcode(0);
        expressinfoModel.noPage();
        List<ExpressinfoModel> expressList = expressinfoService.getList(expressinfoModel);
        List<String> existsOrder = new ArrayList<>();
        for (ExpressinfoModel emodel : expressList) {
            existsOrder.add(emodel.getOrderno());
        }
        String currentDay = DateUtil.getDay();
        RegularsuborderModel regularsuborderModel = new RegularsuborderModel();
        regularsuborderModel.setSendtime(currentDay);
        List<RegularsuborderModel> suborderList = regularsuborderMapper.getList(regularsuborderModel);

        for (RegularsuborderModel suborderModel : suborderList) {
            if (!existsOrder.contains(suborderModel.getSuborderno())) {
                expressService.createRegularSubOrder(suborderModel.getSuborderno());
            }
        }
    }

    //每30秒去取一次订单的配送轨迹数据
    @Scheduled(fixedRate = 1000 * 30)
    public void finshOrder() {
        ExpressrecordModel expressrecordModel = new ExpressrecordModel();
        expressrecordModel.setRecordtype(ConstantVariable.LOAD_POSITION);
        List<ExpressrecordModel> dataList = expressrecordService.getList(expressrecordModel);
        for (ExpressrecordModel emodel : dataList) {
            expressService.riderlatestposition(emodel.getSforderid());
        }
    }


    @Autowired
    private PossubmitorderService possubmitorderService;




    /**
     * 定时把顺丰创建的订单修改成派送中的状态
     */
    @Scheduled(fixedRate = 1000 * 15)
    public void startSendOrder() {

        OrderinfoModel orderinfoModel = new OrderinfoModel();
        orderinfoModel.setSendtime(DateUtil.getDay());
        orderinfoModel.setOrderstatus(ConstantVariable.ORDER_2);
        //sendtime
        List<OrderinfoModel> orderList = orderinfoService.getNeedSendOrder(orderinfoModel);

        RegularsuborderModel nullModel = new RegularsuborderModel();
        List<RegularsuborderModel> subOrderList = regularsuborderMapper.getNeedSendOrder(nullModel);

        Map<String, RegularsuborderModel> regularsuborderMap = new HashMap<>();
        Map<String, OrderinfoModel> orderinfoMap = new HashMap<>();

        List<String> orderNoList = new ArrayList<>();
        for (OrderinfoModel orderModel : orderList) {
            orderNoList.add(orderModel.getOrderno());
            orderinfoMap.put(orderModel.getOrderno(), orderModel);
        }

        for (RegularsuborderModel orderModel : subOrderList) {
            orderNoList.add(orderModel.getSuborderno());
            regularsuborderMap.put(orderModel.getSuborderno(), orderModel);
        }

        try {
            ExpressinfoModel expressinfoModel = new ExpressinfoModel();
            //expressinfoModel.setCreateday(DateUtil.getDay());
            expressinfoModel.setApitype("createorder");
            expressinfoModel.setErrorcode(0);
            expressinfoModel.setShopId(ExpressService.shopId);
            List<ExpressinfoModel> dataList = expressinfoService.getList(expressinfoModel);
            for (ExpressinfoModel expressModel : dataList) {
                String createOrderNo = expressModel.getOrderno();
                if (orderNoList.contains(createOrderNo)) {
                    List<Map<String, Object>> statusList = expressService.listorderfeed(expressModel.getSforderid(), expressModel.getOrderno());
                    String orderStatus = converSfOrderStatus(statusList, createOrderNo);
                    if ("3".equals(String.valueOf(createOrderNo.charAt(14)))) {
                        RegularsuborderModel editRegularModel = regularsuborderMap.get(createOrderNo);
                        if (null != editRegularModel && !orderStatus.equals(editRegularModel.getStatus())) {
                            editRegularModel.setStatus(orderStatus);
                            regularsuborderMapper.update(editRegularModel);
                        }
                    } else if ("1".equals(String.valueOf(createOrderNo.charAt(14)))) {
                        OrderinfoModel editModel = orderinfoMap.get(createOrderNo);
                        if (null != editModel && !orderStatus.equals(editModel.getOrderstatus())) {
                            editModel.setOrderstatus(orderStatus);
                            orderinfoService.update(editModel);
                        }
                    }

                }
            }
        } catch (Exception e) {

        }
    }

    @Autowired
    private ExpressrecordService expressrecordService;

    private String converSfOrderStatus(List<Map<String, Object>> statusList, String orderNo) {
        Integer tip = Integer.parseInt(String.valueOf(orderNo.charAt(14)));
        String sendStatus = "";
        if (CollectionUtils.isEmpty(statusList)) {
            sendStatus = "-1";
        }
        String time = DateUtil.getTime();
        for (Map<String, Object> statusMap : statusList) {
            time = String.valueOf(statusMap.get("create_time"));
            if ("17".equals(statusMap.get("order_status"))) {
                sendStatus = "17";//只要加载了状态17,就不用加载其他状态了
                break;
            } else {
                sendStatus = String.valueOf(statusMap.get("order_status"));
            }
        }
        Calendar calendar = Calendar.getInstance();
        Long orderPushTime = 0L;
        try {
            //毫秒
            calendar.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time));
            orderPushTime = calendar.getTimeInMillis();
        } catch (ParseException e) {
            orderPushTime = System.currentTimeMillis();
        }

        //如果订单完成,就把它从记录表删除
        if ("17".equals(sendStatus)) {
            ExpressrecordModel expressrecordModel = new ExpressrecordModel();
            expressrecordModel.setOrderno(orderNo);
            expressrecordService.deleteByField(expressrecordModel);
        } else if (null == expressrecordService.validateRecord(orderNo, ConstantVariable.LOAD_POSITION)) {
            //如果没有在订单配送表匹配到记录,则新加一条
            ExpressinfoModel expressinfoModel = new ExpressinfoModel();
            expressinfoModel.setOrderno(orderNo);
            expressinfoModel.setApitype("createorder");
            expressinfoModel.setErrorcode(0);
            expressinfoModel = expressinfoService.getModelById(expressinfoModel);
            if (null != expressinfoModel) {
                ExpressrecordModel expressrecordModel = new ExpressrecordModel();
                expressrecordModel.setOrderno(orderNo);
                expressrecordModel.setRecordtype(ConstantVariable.LOAD_POSITION);
                expressrecordModel.setCreatetime(DateUtil.getTime());
                expressinfoModel.setSforderid(expressinfoModel.getSforderid());
                expressrecordService.insert(expressrecordModel);
            }
        }


        if (tip == 3) {
            //定期购
            if (sendStatus == "-1") {
                return ConstantVariable.SUB_ORDER_READY;
            } else if ("17".equals(sendStatus)) {
                if (System.currentTimeMillis() - orderPushTime < 3600 * 8 * 1000) {
                    return ConstantVariable.SUB_ORDER_CURRENT;
                } else {
                    return ConstantVariable.SUB_ORDER_FINSH;
                }
            } else {
                return ConstantVariable.SUB_ORDER_CURRENT;
            }
        } else {
            //普通订单
            if (sendStatus == "-1") {
                return ConstantVariable.ORDER_2;
            } else if ("17".equals(sendStatus)) {
                if (System.currentTimeMillis() - orderPushTime < 3600 * 8 * 1000) {
                    return ConstantVariable.ORDER_READY_PULL;
                } else {
                    return ConstantVariable.ORDER_READY_EVAL;
                }
            } else {
                return ConstantVariable.ORDER_3;
            }
        }
    }


}